package com.hc.tenant.listener;

import com.alibaba.fastjson.JSON;
import com.hc.common.core.utils.StringUtils;
import com.hc.common.security.service.TokenService;
import com.hc.tenant.domain.RobotInfo;
import com.hc.tenant.listener.event.MqttEvent;
import com.hc.tenant.listener.event.RobotInfoEvent;
import com.hc.tenant.service.IRobotInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RobotInfoListener implements MqttEventListener {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private IRobotInfoService robotInfoService;
    @Override
    public void onMqttEvent(MqttEvent mqttEvent) {
        if(StringUtils.equals(RobotInfoEvent.EVENT_NAME,(String) mqttEvent.getSource())){
            String token = mqttEvent.getToken();
            String payLoad = new String (mqttEvent.getMqttMessage().getPayload());
            Long userId = tokenService.getLoginUser(token).getUserid();
            RobotInfo robotInfo = JSON.parseObject(payLoad, RobotInfo.class);
            boolean robotInfoExist = robotInfoService.selectRobotInfoByUserId(userId) != null;
            robotInfo.setUserId(userId);
            robotInfo.getCurrentGpsLocation().setUserId(userId);
            if(robotInfoExist){
                robotInfoService.updateRobotInfo(robotInfo);
            }else{
                robotInfoService.insertRobotInfo(robotInfo);
            }
        }
    }
}
